<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用户输入表单</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</head>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
<style>
	.box{
		margin:20px auto;
		width:300px;
		height:200px;
	}
	.box1{
		display:flex;
		height: 40px;
	}
	.price_titile{
	margin-left:10px;
		display:inline-block;
		width:100px;
		height:50px;
		text-align:center;
		line-height: 50px;
	}
	.price{
		width:100px;
		height:50px;
		font-size:18px;
		
		text-align:center;
		line-height: 50px;
	}
	.buyBtn{
		    margin-top: 10px;
    		float: right;
	}
	
	.num{
		display:inline-block; 
		margin-top:10px;
		height: 40px;
	}
</style>
<body>
	<div class="box">
		<form onSubmit="return false">
			<div class="box1">
				<select class="goodsName goodsDom  form-select">
				 <option selected>----选择商品----</option>
				</select>
				<span class="price_titile">价格：</span><p class="price"></p>
			</div>
		<input class="num form-control" type="text" name="num" placeholder="请输入购买商品数量">
		<button type="button" class="btn btn-primary buyBtn" onclick="buy()">提交</button>
		</form>
	</div>
</body>

<script>
	var goodsDom=$('.goodsDom');
	var str1='';
	$.get({
		url:'./goods.json',
		success:function(res){
			for(let item of res){
				str1+='<option value="'+ item['goodsName'] +'">'+item['goodsName']+'</option>';
				
			}
			goodsDom.append(str1);
		}
	})
	//事件监听
	goodsDom.change(function(e){
		$.get({
			url:'./goods.json',
			success:function(res){
				for(let item of res){
					if(item.goodsName==e.target.value){
						$('.price').text(item.price);
					}
				}
			}
		})
		
	})
	function buy(){
		const goodsName=$('.goodsName').val();
		const price=$('.price').text();
		const num=$('.num').val();
		console.log(goodsName);
		console.log(price);
		console.log(num);
		$.ajax({
			url:"${pageContext.request.contextPath}/goods.jsp",
			type:"post",
			data:{
				"goodsName":goodsName,
				"price":price,
				"num":num
			},
			success:function(){
				console.log("ok");
				//跳转页面
				window.location="${pageContext.request.contextPath}/goods.jsp"
				
			}
		})
	}
</script>
</html>